import { ExtendedCss } from "@adguard/extended-css";
import { canApplyCss } from "./bRuleSupport.mjs";
import { debug, features, speedOnly } from "./buildConfig.mjs";
import { downUrl, gmMenu, values, getSavedHosts } from "./gmBridge.mjs";
import { cssToAbp, styleBoxes } from "./util.mjs";
import { data } from "./globalData.mjs";
import { logger } from "./logger.mjs";

/**
 * 清空存储规则并更新脚本菜单
 */
export async function cleanRules() {
  if (
    confirm(
      `是否清空存储规则 ?

如果要卸载脚本，点击 确定 以后不要刷新，也不要打开任何新页面，
（如果可以）立即清空脚本存储（全选，删除，填 {}，保存），然后删除脚本`,
    )
  ) {
    await values.rules(null);
    await values.time(null);
    await values.etags(null);
    await values.brules(null);
    const saves = await getSavedHosts();
    for (const save of saves) {
      await values.css(null, save);
    }
    data.isClean = true;
    if (features.update) await gmMenu("update");
    await gmMenu("export");
    await gmMenu("count", () => {
      location.reload();
    });
    return;
  }
}

/**
 * 生成并自动下载广告拦截报告
 */
export function reportRecord() {
  let text = "";
  const records: [string, number][] = [];
  function pushRecord(css: string) {
    const match = cssToAbp(css);
    if (match === null) return;
    const { abp: item, type, sel } = match,
      count: number =
        type % 2 === 1
          ? (ExtendedCss.query(sel) as Element[]).length
          : document.querySelectorAll(sel).length;
    if (count > 0) {
      text += `
! 匹配元素数量: ${String(count)}
${item}
`;
      debug && !speedOnly && records.push([item, count]);
    }
  }

  for (const br of data.bRules) {
    if (br.level > 0) {
      text += `
! 禁用${["", "通用", "特定", "所有"][br.level]}元素隐藏
${br.rule}
`;
    }
  }

  for (const [index, box] of styleBoxes.entries()) {
    if (canApplyCss(index as 0 | 1 | 2 | 3)) {
      for (const css of data[box]
        .split("\n")
        .filter((css, index_, csss) => csss.indexOf(css) === index_))
        pushRecord(css);
    }
  }

  if (debug && !speedOnly) {
    logger("info", "页面地址: " + location.href);
    if (records.length > 0) {
      logger("data", records);
    }
  }

  if (text.length > 0) {
    const blobUrl = URL.createObjectURL(
      new Blob([
        `[Adblock Plus 2.0]
! 应用地址:
! ${location.href}
${text}`,
      ]),
    );
    if (debug && !speedOnly) {
      logger("info", "报告地址: " + blobUrl);
    }
    downUrl(blobUrl, `拦截报告_${location.hostname}.txt`);
  } else {
    alert("这个页面没有任何规则生效");
  }
}

/**
 * 切换网站禁用状态并自动刷新
 */
export async function switchDisabledStat() {
  const disaList = await values.black();
  const disas = disaList ?? [];
  data.disabled = !disas.includes(location.hostname);
  if (data.disabled) {
    disas.push(location.hostname);
  } else {
    disas.splice(disas.indexOf(location.hostname), 1);
  }
  await values.black(disas);
  location.reload();
}
